package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.mapper.LoginMapper;
import com.itheima.mapper.UserLoginMapper;
import com.itheima.pojo.Employee;
import com.itheima.pojo.Login;
import com.itheima.pojo.User;
import com.itheima.service.LoginService;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.SMSUtils2;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author: 放学后海堤日记
 * @Date: 2023/4/13 11:08
 * @Desc:
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private UserLoginMapper userLoginMapper;

    @Override
    public Employee login(String username, String password, HttpServletRequest request) {
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username).eq("password", password);
        Employee employee = loginMapper.selectOne(wrapper);

        if (employee != null && employee.getStatus() != 0) {
            request.getSession().setAttribute("employeeId", employee.getId());

            return employee;
        }

        return null;
    }

    /**
     * 用户登录
     * @param login
     * @param request
     * @return
     */
    @Override
    public int login(Login login, HttpServletRequest request) {
        String code = (String) request.getSession().getAttribute("code");

        if (!login.getCode().equals(code))
            return 0;

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", login.getPhone());

        User user = userLoginMapper.selectOne(wrapper);
        if (user == null) {
            user.setStatus(1);
            userLoginMapper.insert(user);
            user = userLoginMapper.selectOne(wrapper);
        } else if (user.getStatus() == 0)
            return 0;

        request.getSession().setAttribute("userId", user.getId());

        //登录成功抹除浏览器保存的验证码，避免被重复登录使用
        request.getSession().removeAttribute("code");

        return 1;
    }

    /**
     * 发送短信验证码
     * @param phone
     * @param session
     * @return
     */
    @Override
    public void sendMsg(String phone, HttpSession session) {
        String code = ValidateCodeUtils.generateValidateCode(6).toString();
        SMSUtils2.sendMessage("study", "SMS_276445791", phone, code);

        session.setAttribute("code", code);
    }
}
